<?php

declare(strict_types=1);

namespace app\common\model;

use think\facade\Event;

class Product extends Base
{
    protected $name = 'product';

    public function cate1()
    {
        return $this->hasOne(ProductCate::class, 'id', 'cate_1')->field('id,title');
    }

    public function merchant()
    {
        return $this->hasOne(Merchant::class, 'id', 'merchant_id')->field('id,title');
    }
    public function cate2()
    {
        return $this->hasOne(ProductCate::class, 'id', 'cate_2')->field('id,title');
    }

    public function getSpecDataAttr($val, $data)
    {
        return $data['spec'] ? json_decode($data['spec'], true) : [];
    }

    public static function productDelete($param, $logs): array
    {
        try {
            if (is_array($param['id'])) {
                self::destroy($param['id']);
                $model = (object)[];
                $logs['operation'] = 'deleteAll';
                $model->ids = $param['id'];
            } else {
                $model = self::where($logs['pk'], $param['id'])->find();
                self::destroy($param['id']);
                $logs['operation'] = 'delete';
            }
            if ($logs['writeLog']) {
                $logs['model'] = $model;
                Event::trigger('Logs', $logs);
            }

            ProductSpec::destroy(['pid' => $param['id']], true);
            return ['code' => 1, 'msg' => '已删除'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 上下架
     */

    public static function productRacks($param): array
    {
        try {
            if($param['type'] == 1){
                $msg = '上架成功！请等待后台审核！';
                // $data['status'] =1;
                $data['is_audit'] =1;
            }else{
                $msg = '下架成功';
                $data['status'] =0;
            }
            parent::where('id',$param['id'])->update($data);
            return ['code' => 1, 'msg' => $msg];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
 /**
     * 批量审核
     */
    public static function batch($ids, $admin): array
    {
        parent::startTrans();
        try {
            // print('<pre>');print_r($ids);die;
            $infos = parent::whereIn('id', $ids)->select();
            if ($infos->isEmpty()) {
                return ['code' => -1, 'msg' => '未查询到待审核的数据，请检查！'];
            }
            parent::whereIn('id',$ids)->update(['status' => 1,'is_audit'=>2]);
            parent::commit();
            $msg = '批量通过商品添加申请,标识ID【' . implode(',', $ids) . '】';
            Logs::adds($msg, $admin['id'], $admin['admin_name']);
           
            return ['code' => 1, 'msg' => '已批量审核'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function _save($param, $logs): array
    {
        parent::startTrans();
        try {


            if (!empty($param['images'])) {
                $param['icon'] = explode(',', $param['images'])[0];
            }
            // var_dump($param);die;
            if (!empty($param['id'])) {
                if($param['shop_type'] == 2){
                    if(isset($param['is_audit'])){
                        if($param['is_audit'] == 2){
                            $param['status'] = 1;
                        }
                    }
                }
                $product = parent::update($param);
                $product->operation = 'save';
            } else {
                $param['initOk'] = 'true';
                $param['is_audit'] = 2;
                $product = parent::create($param);
                $product->operation = 'create';
            }
            // if ($param['spec_open'] == 2 && $param['initOk'] == 'true') {
            //     $specVale = [];
            //     $min = [];
            //     $stock = 0;
            //     $stockFiled = '';
            //     foreach ($param['tableSpec'] as $value) {
            //         $mergeId = [];
            //         $mergeTitle = [];
            //         foreach ($value as $k => $item) {
            //             $title = explode('spec$$Title_', $k);
            //             if (count($title) > 1) {
            //                 $mergeId[] = $title[1];
            //                 $mergeTitle[] = $item;
            //             }
            //         }
            //         $tapeVale = [];
            //         foreach ($param['tape'] as $tape) {
            //             $tapeVale[$tape['field']] = $value[$tape['field']];
            //             if (empty($tape['type'])) {
            //                 if (empty($min[$tape['field']])) {
            //                     $min[$tape['field']] = $value[$tape['field']];
            //                 } else {
            //                     $min[$tape['field']] = $value[$tape['field']] < $min[$tape['field']] ? $value[$tape['field']] : $min[$tape['field']];
            //                 }
            //             } else if ($tape['type'] == 'stock') {
            //                 $stockFiled = $tape['field'];
            //                 $stock += intval($value[$tape['field']]);
            //             }
            //         }
            //         $mergeVale = [
            //             'pid'         => $product->id,
            //             'icon'        => $value['icon'],
            //             'merge_id'    => implode(',', $mergeId),
            //             'merge_title' => implode(',', $mergeTitle)
            //         ];
            //         $specVale[] = array_merge($tapeVale, $mergeVale);
            //     }

            //     //清除旧规格
            //     if (!empty($form['id'])) {
            //         ProductSpec::destroy(['pid' => $form['id']], true);
            //     }
            //     //填写新规格
            //     (new ProductSpec())->insertAll($specVale);

            //     $product->spec = json_encode($param['spec']);
            //     $product->table_spec = json_encode($param['tableSpec']);
            //     foreach ($min as $k => $v) {
            //         $product->$k = $v;
            //     }
            //     $product->$stockFiled = $stock;
            //     $product->save();
            // }

            parent::commit();
            Event::trigger('Logs', $product);
            return ['code' => 1, 'msg' => '已保存'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    public static function saveProduct($param): array
    {
        parent::startTrans();
        try {
            if (!empty($param['images'])) {
                $param['icon'] = explode(',', $param['images'])[0];
            }
            // var_dump($param);die;
            if (!empty($param['id'])) {
                $news = parent::update($param);
            } else {
                $param['status'] = 0;
                $news = parent::create($param);
            }
            parent::commit();
            return ['code' => 1, 'msg' => '已保存'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
